//
//  SXQRCodeReader.m
//  尚秀授权
//
//  Created by Guangtao Li on 13-10-7.
//  Copyright (c) 2013年 sunshow-imac. All rights reserved.
//

#import "SXQRCodeReader.h"
#import <ZXingWidgetController.h>
#import <QRCodeReader.h>
#import <TwoDDecoderResult.h>

@interface SXQRCodeReader ()<DecoderDelegate>

@end


@implementation SXQRCodeReader
- (id)initWithImage:(UIImage *)image delegate:(id<SXQRCodeReaderDelegate>) delegate
{
    self = [super init];
    if (self) {
        QRCodeReader* qrcodeReader = [[QRCodeReader alloc] init];
        self.delegate = delegate;
        
        Decoder *d = [[Decoder alloc] init];
        [d setDelegate:self];
        [d setReaders:[[NSSet alloc ] initWithObjects:[qrcodeReader autorelease],nil]];
        
        BOOL decodeSuccess= [d decodeImage:image];
        NSLog(@"BOOL = %@\n", (decodeSuccess ? @"YES" : @"NO"));
    }
    return self;
}



- (void)decoder:(Decoder *)decoder didDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset withResult:(TwoDDecoderResult *)result{
    [result retain];
    NSLog(@"Did Decode Image Result: %@",result.text);
    [result release];
    
    NSString *resultStr = result.text;
    NSArray *strArray = [resultStr componentsSeparatedByString:@"-"];
    NSString *miniCode = nil;
    NSString *padCode = nil;
    if (strArray.count>0)
    {
        padCode = [strArray objectAtIndex:0];
    }
    
    if (strArray.count>1) {
        miniCode = [strArray objectAtIndex:1];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(decodedWithMiniCode:padCode:)]) {
        [self.delegate decodedWithMiniCode:miniCode padCode:padCode];
    }
    
    
}

- (void)decoder:(Decoder *)decoder failedToDecodeImage:(UIImage *)image usingSubset:(UIImage *)subset reason:(NSString *)reason;
{
    [reason retain];
    NSLog(@"Failed Decode Image Result: %@",reason);
    [reason release];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(decodeFaild)]) {
        [self.delegate decodeFaild];
    }
}
@end
